/*
 * Copyright (C) 2011 Lavettacn Xiao (lavettacn@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lavettacn.android.app.sociallessness.fragment;

import com.lavettacn.android.app.sociallessness.R;
import com.lavettacn.android.app.sociallessness.account.AccountContentProvider;
import com.lavettacn.android.app.sociallessness.data.table.TableElement;
import com.lavettacn.android.app.sociallessness.service.BaseService;
import com.lavettacn.android.app.sociallessness.service.ServiceManager;
import com.lavettacn.android.app.sociallessness.util.Debug;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class AccountManagerFragment extends BaseListFragment implements OnClickListener,
        LoaderManager.LoaderCallbacks<Cursor> {

    public static final String TAG = "AccountManagerFragment";

    private Button mAddButton;
    private ServiceManager mServiceManager;
    private Spinner mSpinner;
    private SimpleCursorAdapter mAdapter;
    private TextView mEmptyView;

    public static AccountManagerFragment newInstance(ServiceManager manager) {
        AccountManagerFragment f = new AccountManagerFragment(manager);
        return f;
    }

    private AccountManagerFragment(ServiceManager manager) {
        mServiceManager = manager;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Debug.logD(getTag(), ": onCreateView");
        View view = inflater.inflate(R.layout.account_manager, container, false);
        mSpinner = (Spinner)view.findViewById(R.id.add_account_spinner);
        mSpinner.setPromptId(R.string.add_account_txt);
        mSpinner.setAdapter(new ServiceAdapter(getActivity(), mServiceManager.getAllServices()));
        mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int position,
                            long id) {
                        Debug.logD(getTag(), ": onItemSelected, position=" + position);
                        BaseAdapter adapter = (BaseAdapter)parent.getAdapter();
                        BaseService service = (BaseService)adapter.getItem(position);
                        if (service != null) {
                            service.login(getActivity());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
        mEmptyView = (TextView) view.findViewById(android.R.id.empty);
        mEmptyView.setText(R.string.no_account_txt);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Debug.logD(getTag() + ": onActivityCreated");
        mAdapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_list_item_2, null,
                new String[] { TableElement.ACCOUNT_NAME,TableElement.SERVICE_TYPE },
                new int[] { android.R.id.text1, android.R.id.text2 }, 0);
        setListAdapter(mAdapter);
        getLoaderManager().initLoader(getLoaderId(), null, this);
    }

    public void onClick(View view) {
        if (view == mAddButton) {
            showServiceList();
        }
    }

    public int getLoaderId() {
        return 0;
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(), AccountContentProvider.ACCOUNT_URI,
                null, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        Debug.logD(TAG, "onLoadFinished, cursor=" + cursor);
        mAdapter.swapCursor(cursor);
    }

    public void onLoaderReset(Loader<Cursor> cursor) {
        Debug.logD(TAG, "onLoaderReset, cursor=" + cursor);
        mAdapter.swapCursor(null);
    }

    private void showServiceList() {
    }

    private class ServiceAdapter extends BaseAdapter {

        private BaseService[] mServices;
        private Context mContext;

        public ServiceAdapter(Context context, BaseService[] services) {
            mContext = context;
            mServices = services;
        }

        public int getCount() {
            return mServices.length + 1;
        }

        public Object getItem(int position) {
            if (position > 0) {
                return mServices[position - 1];
            }
            return null;
        }

        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            if (position == 0) {
                return createEmptyView();
            }
            RelativeLayout listItem;
            BaseService service = mServices[position - 1];
            if (convertView != null && convertView instanceof RelativeLayout){
                listItem = (RelativeLayout) convertView;
            } else {
                listItem = (RelativeLayout) LayoutInflater.from(mContext)
                        .inflate(R.layout.service_list_item, parent, false);
            }
            TextView title = (TextView)listItem.findViewById(R.id.service_list_item_title_text);
            TextView description = (TextView)listItem.findViewById(R.id.service_list_item_description_text);
            ImageView icon = (ImageView)listItem.findViewById(R.id.service_list_item_image);

            title.setText(service.getServiceNameId());
            description.setText(service.getServiceDescriptionId());
            icon.setImageResource(service.getServiceIconID());
            return listItem;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            RelativeLayout listItem;
            if (convertView != null && convertView instanceof RelativeLayout){
                listItem = (RelativeLayout) convertView;
            } else {
                listItem = (RelativeLayout) LayoutInflater.from(mContext)
                        .inflate(R.layout.service_list_item, parent, false);
            }

            TextView title = (TextView)listItem.findViewById(R.id.service_list_item_title_text);
            TextView description = (TextView)listItem.findViewById(R.id.service_list_item_description_text);
            ImageView icon = (ImageView)listItem.findViewById(R.id.service_list_item_image);

            title.setText(R.string.add_account_txt);
            description.setVisibility(View.GONE);
            icon.setVisibility(View.GONE);
            return listItem;
        }

        private View createEmptyView() {
            View view = new View(mContext);
            view.setVisibility(View.GONE);
            return view;
        }
    }

}
